package com.yinhai.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yinhai.adapter.CloudNoteAdapter;
import com.yinhai.adapter.CloudNotePopAdapter;
import com.yinhai.asynctask.AsyncTaskParam;
import com.yinhai.asynctask.BackupCloudNoteTask;
import com.yinhai.asynctask.FindCloudNoteTask;
import com.yinhai.asynctask.NameValueParam;
import com.yinhai.cfg.AppConfig;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.CloudNote;
import com.yinhai.service.CloudNoteServiceImpl;

public class CloudNoteActivity extends Activity {
	private String select_uuid = "1";
	private String select_note = "";
	private String phone;
	private ImageView iv_back, iv_add, iv_backup, iv_hf;
	private RelativeLayout rl_main, rl_buttom;
	private TextView tv_title;
	private PopupWindow imPopWindow;

	ListView popSortListView, dataListView;
	BaseAdapter adapter = null;
	CloudNote selectCn;

	List<CloudNote> popSortList, dataList;

	private CloudNoteServiceImpl cnServiceIpml;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cloudnote);
		dataList = new ArrayList<CloudNote>();
		popSortList = new ArrayList<CloudNote>();
		CloudNoteActivity.this.registerReceiver(cnReceiver, new IntentFilter(
				"com.cloudnote.update"));
		SharedPreferences preferences = getSharedPreferences(
				AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
		phone = preferences.getString("name", "");
		rl_main = (RelativeLayout) findViewById(R.id.note_main);
		tv_title = (TextView) findViewById(R.id.txt_contact);
		iv_back = (ImageView) findViewById(R.id.btn_back);
		iv_add = (ImageView) findViewById(R.id.btn_add);
		iv_backup = (ImageView) findViewById(R.id.btn_backup);
		iv_hf = (ImageView) findViewById(R.id.btn_hf);
		dataListView = (ListView) findViewById(R.id.listview);
		iv_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		iv_add.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CloudNoteActivity.this,
						CloudNoteContentActivity.class);
				intent.putExtra("pid", select_uuid);
				intent.putExtra("type", "add");
				intent.putExtra("uuid", "");
				CloudNoteActivity.this.startActivity(intent);
			}
		});
		tv_title.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initSort();
			}
		});
		iv_backup.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				cnServiceIpml = new CloudNoteServiceImpl(CloudNoteActivity.this);
				if (cnServiceIpml.isNeedBackUp()) {
					new BackupAsyncTask().execute();
				} else {
					Toast.makeText(CloudNoteActivity.this, "无需备份",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		iv_hf.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new FindCloudNoteAsyncTask().execute();
			}
		});

		
		init();

	}

	void initSort() {
		new SortAsyncTask().execute();
	}

	ProgressDialog progressDialog = null;

	private class BackupAsyncTask extends AsyncTask<Void, Void, Integer> {
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progressDialog.cancel();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog = new ProgressDialog(CloudNoteActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("正在备份云笔记");
			progressDialog.show();
			// super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			BackupCloudNoteTask backupCloudNoteTask = new BackupCloudNoteTask(
					CloudNoteActivity.this);
			AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI
					+ UrlConstant.BACK_CLOUDNOTE);
			List<NameValuePair> postParam = new ArrayList<NameValuePair>();
			NameValueParam nvp = new NameValueParam();
			nvp.setName("phone");
			nvp.setValue(phone);
			postParam.add(nvp);

			nvp = new NameValueParam();
			nvp.setName("note");
			nvp.setValue(cnServiceIpml.getCloudBuckUpData(phone));
			postParam.add(nvp);
			taskParam.setPostParam(postParam);
			backupCloudNoteTask.execute(taskParam);
			return 0;
		}

	}

	private class FindCloudNoteAsyncTask extends AsyncTask<Void, Void, Integer> {
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progressDialog.cancel();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog = new ProgressDialog(CloudNoteActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("正在恢复云笔记");
			progressDialog.show();
			// super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			FindCloudNoteTask findCloudNoteTask = new FindCloudNoteTask(
					CloudNoteActivity.this);
			AsyncTaskParam taskParam = new AsyncTaskParam(UrlConstant.LOCAL_URI
					+ UrlConstant.FIND_CLOUDNOTE);
			List<NameValuePair> postParam = new ArrayList<NameValuePair>();
			NameValueParam nvp = new NameValueParam();
			nvp.setName("phone");
			nvp.setValue(phone);
			postParam.add(nvp);
			taskParam.setPostParam(postParam);
			findCloudNoteTask.execute(taskParam);
			return 0;
		}

	}

	private BroadcastReceiver cnReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals("com.cloudnote.update")) {
				intent.getStringExtra("");
				if (intent.getStringExtra("bc_uuid") != null
						&& intent.getStringExtra("is_del") != null) {
					if (intent.getStringExtra("bc_uuid").equals(select_uuid)) {
						if (intent.getStringExtra("is_del").toString()
								.equals("1")) {
							new SortContentListAsyncTask().execute("1");
						} else {
							new SortContentListAsyncTask().execute(select_uuid);
						}
					} else if (intent.getStringExtra("bc_uuid").equals("-2")) {
						new SortContentListAsyncTask().execute("1");
					}
				}
			}
		}

	};

	private class SortAsyncTask extends AsyncTask<Void, Void, Integer> {
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			if (popSortList != null && popSortList.size() > 0) {
				adapter = new CloudNotePopAdapter(CloudNoteActivity.this,
						popSortList);
				LayoutInflater inflater = (LayoutInflater) CloudNoteActivity.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				View popView = inflater.inflate(R.layout.pop_cloudnote_allsort,
						null);
				popSortListView = (ListView) popView
						.findViewById(R.id.sort_listview);
				popSortListView.setAdapter(adapter);
				popSortListView
						.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								// TODO Auto-generated method stub
								if (imPopWindow != null) {
									imPopWindow.dismiss();
								}
								if (popSortList.get(arg2).getUuid().equals("0")) {
									Intent intent = new Intent(
											CloudNoteActivity.this,
											CloudNoteSortActivity.class);
									CloudNoteActivity.this
											.startActivity(intent);
								} else {
									select_uuid = popSortList.get(arg2)
											.getUuid();
									// tv_title.setText(popSortList.get(arg2).getNote());
									new SortContentListAsyncTask()
											.execute(popSortList.get(arg2)
													.getUuid());
								}
							}
						});

				imPopWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				imPopWindow.setFocusable(true);
				imPopWindow.setBackgroundDrawable(CloudNoteActivity.this
						.getResources().getDrawable(
								R.drawable.quickaction_popup));
				imPopWindow.setOutsideTouchable(true);
				imPopWindow.update();

				if (!imPopWindow.isShowing()) {
					imPopWindow.showAtLocation(rl_main, Gravity.CENTER, 0, 0);
				} else {
					imPopWindow.dismiss();
				}
			}
			// super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (popSortList != null && popSortList.size() > 0) {
				popSortList.clear();
			}

			cnServiceIpml = new CloudNoteServiceImpl(CloudNoteActivity.this);
			popSortList = cnServiceIpml.getPopSortList();

			return 0;
		}

	}

	void init() {
		new SortContentListAsyncTask().execute("1");
	}

	private class SortContentListAsyncTask extends
			AsyncTask<String, Void, Integer> {
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			/*
			 * if(dataList!=null && dataList.size()>0){
			 * 
			 * }
			 */
//		    if(select_note.equals("")){
		        tv_title.setText(select_note==null?"":select_note);
//		    }
			adapter = new CloudNoteAdapter(CloudNoteActivity.this, dataList);
			dataListView.setAdapter(adapter);
			dataListView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(CloudNoteActivity.this,
							CloudNoteContentActivity.class);
					intent.putExtra("pid", dataList.get(arg2).getPid());
					intent.putExtra("type", "edit");
					intent.putExtra("uuid", dataList.get(arg2).getUuid());
					CloudNoteActivity.this.startActivity(intent);
				}
			});

		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(String... params) {
			// TODO Auto-generated method stub
			cnServiceIpml = new CloudNoteServiceImpl(CloudNoteActivity.this);
			if (dataList != null && dataList.size() > 0) {
				dataList.clear();
			}
			CloudNote c = cnServiceIpml.getCloudNoteByUuid(params[0]);
			if(c !=null){
			    select_note = c.getNote();
			}else{
			    if(select_note.equals("")){
                    select_note ="默认分类";
                }
			}
			if(cnServiceIpml.getSortList(params[0]).size() !=0){
			    dataList.addAll(cnServiceIpml.getSortList(params[0]));
			}
			
			return 0;
		}

	}

	public OnClickListener DelItme = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			selectCn = (CloudNote) v.getTag();
			AlertDialog dlg = new AlertDialog.Builder(CloudNoteActivity.this)
					.setIcon(0)
					.setTitle("删除记录")
					.setMessage("您确定删除该记录!")
					.setPositiveButton("删除",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									cnServiceIpml = new CloudNoteServiceImpl(
											CloudNoteActivity.this);
									cnServiceIpml.deleteMainData(selectCn
											.getUuid());
									dataList.remove(selectCn);
									adapter.notifyDataSetChanged();
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.dismiss();
								}
							}).create();
			dlg.show();
		}
	};

	@Override
	public void onDestroy() {
		unregisterReceiver(cnReceiver);
		super.onDestroy();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (imPopWindow != null && imPopWindow.isShowing()) {
			imPopWindow.dismiss();
			imPopWindow = null;
		}
		return super.onTouchEvent(event);

	}

}
